<?php

namespace App\Models;



use App\Tool\Helper;
use Illuminate\Support\Facades\DB;

/**
 * App\Models\Orders
 *
 * @property int $id
 * @property int|null $user_id 用户id
 * @property string|null $no 订单编号
 * @property string|null $total_money 订单总价
 * @property string|null $payd_at 支付时间
 * @property string|null $send_at 发货时间
 * @property string|null $overd_at 收货时间
 * @property int|null $is_pay 支付状态（0：未支付，1：已支付）
 * @property int|null $status 订单状态（0：待支付，1：待发货，2：待收货，3：待评价，4：已完成，5：退款售后）
 * @property int|null $type 类型（1：实物订单，2：预约服务订单）
 * @property int|null $is_write 核销（0：待核销，1：已核销）
 * @property int|null $address_id 收货地址id
 * @property string|null $address_name 收货人姓名
 * @property string|null $address_phone 收货人电话
 * @property int|null $province_id 收货地址省id
 * @property int|null $city_id 收货地址市id
 * @property int|null $area_id 收货地址区id
 * @property string|null $province_name 收货地址省名称
 * @property string|null $city_name 收货地址市名称
 * @property string|null $area_name 收货地址区名称
 * @property string|null $address_detail 收货地址详细地址
 * @property \Illuminate\Support\Carbon|null $created_at 创建时间
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|Orders newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Orders newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Orders query()
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereAddressDetail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereAddressId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereAddressName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereAddressPhone($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereAreaId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereAreaName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereCityId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereCityName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereIsPay($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereIsWrite($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereNo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereOverdAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders wherePaydAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereProvinceId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereProvinceName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereSendAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereTotalMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereUserId($value)
 * @mixin \Eloquent
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\OrdersGoods[] $goods
 * @property-read int|null $goods_count
 * @property int|null $is_comment 是否评论（1:已评论，0:未评论）
 * @method static \Illuminate\Database\Eloquent\Builder|Orders whereIsComment($value)
 */
class Orders extends Base
{
    protected $table = 'orders';

    public function goods()
    {
        return $this->hasMany(OrdersGoods::class);
    }

    // 创建订单
    static function add($user_id, $address_id, $goods_info)
    {
        $address = Address::find($address_id);

        try {
            DB::beginTransaction();
            $goodsBySw = []; // 实物商品
            $goodsBySe = []; // 服务商品
            $totalMoneySw = 0;
            $totalMoneySe = 0;
            foreach ($goods_info as $value) {
                $goods = Goods::whereId($value['goods_id'])->lockForUpdate()->first();
                if ($goods->type == 1) {
                    $goods->buy_count = $value['buy_count'];
                    $goodsBySw[] = $goods;
                    $totalMoneySw = bcadd($totalMoneySw, bcmul($goods->price, $value['buy_count']));
                } else {
                    // 服务订单 - 1个商品创建1个订单
                    $ordersSe = new Orders();
                    $ordersSe->user_id = $user_id;
                    $ordersSe->no = 'SE'.date('YmdHis').Helper::createRandNum(6);
                    $ordersSe->total_money = bcmul($goods->price, $value['buy_count']);
                    $ordersSe->is_pay = 0;
                    $ordersSe->status = 0;
                    $ordersSe->type = 2;
                    $ordersSe->address_id = $address_id;
                    $ordersSe->address_name = $address->name;
                    $ordersSe->address_phone = $address->phone;
                    $ordersSe->province_id = $address->province_id;
                    $ordersSe->city_id = $address->city_id;
                    $ordersSe->area_id = $address->area_id;
                    $ordersSe->province_name = $address->province_name;
                    $ordersSe->city_name = $address->city_name;
                    $ordersSe->area_name = $address->area_name;
                    $ordersSe->save();

                    $ordersGoods = new OrdersGoods();
                    $ordersGoods->user_id = $user_id;
                    $ordersGoods->orders_id = $ordersSe->id;
                    $ordersGoods->goods_id = $goods->id;
                    $ordersGoods->category_id = $goods->category_id;
                    $ordersGoods->category_name = $goods->category_name;
                    $ordersGoods->name = $goods->name;
                    $ordersGoods->cover = $goods->cover;
                    $ordersGoods->cover = $goods->cover;
                    $ordersGoods->price = $goods->price;
                    $ordersGoods->buy_num = $value['buy_count'];
                    $ordersGoods->type = 2;
                    $ordersGoods->save();
                }

                // 减库存
                $goods->stock_num = $goods->stock_num - $value['buy_count'];
                if ($goods->stock_num < 0) {
                    throw new \Exception('库存不足～～～');
                }
                $goods->save();
            }

            // 创建实物订单
            if ($totalMoneySw) {
                $orders = new Orders();
                $orders->user_id = $user_id;
                $orders->no = 'SW'.date('YmdHis').Helper::createRandNum(6);
                $orders->total_money = $totalMoneySw;
                $orders->is_pay = 0;
                $orders->status = 0;
                $orders->type = 1;
                $orders->address_id = $address_id;
                $orders->address_name = $address->name;
                $orders->address_phone = $address->phone;
                $orders->province_id = $address->province_id;
                $orders->city_id = $address->city_id;
                $orders->area_id = $address->area_id;
                $orders->province_name = $address->province_name;
                $orders->city_name = $address->city_name;
                $orders->area_name = $address->area_name;
                $orders->save();

                // 订单实物商品入订单商品表
                $ordersGoodsValues = [];
                foreach ($goodsBySw as $goods) {
                    $ordersGoodsValues[] = [
                        'user_id' => $user_id,
                        'orders_id' => $orders->id,
                        'goods_id' => $goods->id,
                        'category_id' => $goods->category_id,
                        'category_name' => $goods->category_name,
                        'name' => $goods->name,
                        'cover' => $goods->cover,
                        'price' => $goods->price,
                        'buy_num' => $goods->buy_count,
                        'type' => $goods->type,
                        'created_at' => $orders->created_at,
                        'updated_at' => $orders->created_at,
                    ];
                }
                OrdersGoods::insert($ordersGoodsValues);
            }

            DB::commit();
            // 创建成功 - 返回支付信息
        } catch (\Exception $exception) {
            \Log::error($exception);
            DB::rollBack();
        } catch (\Throwable $e) {
            \Log::error($e);
            DB::rollBack();
        }
    }
}
